package com.bluefox.uac.controller;

import com.bluefox.common.web.dto.result.PageResultDTO;
import com.bluefox.common.web.dto.result.ResultDTO;
import com.bluefox.common.web.exception.CustomRuntimeException;
import com.bluefox.uac.convertor.UserConvertor;
import com.bluefox.uac.dto.UserDTO;
import com.bluefox.uac.model.User;
import com.bluefox.uac.repository.UserRepository;
import com.bluefox.uac.security.LoginUserBean;
import com.bluefox.uac.service.UserService;
import com.bluefox.uac.utils.SecurityUtils;
import com.bluefox.uac.vo.UserPassVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * User的管理接口
 *
 * @author SunFeng
 */
 @Slf4j
@RestController
@RequestMapping("/w/users")
public class UserController {
    @Autowired
    private UserService userService;
	@Autowired
    private UserRepository userRepository;
    @Autowired
    private UserConvertor userConvertor;

    /**
     * 获取分页数据
     *
     * @param pageable 分页+排序参数
     * @return 分页数据
     */
    @RequestMapping(value = "/s", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public PageResultDTO<UserDTO> search(final Pageable pageable) {
        final Page<User> models = this.userRepository.findAll(pageable);
        return this.userConvertor.toResultDTO(models);
    }

    /**
     * 取得详细数据
     *
     * @param id 资源ID
     * @return 资源详细
     */

    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResultDTO<UserDTO> get(@PathVariable final Long id) {
        final User model = this.userService.get(id);
        return this.userConvertor.toResultDTO(model);
    }

    /**
     * 新建操作
     *
     * @param userDTO 新建资源的DTO
     * @return 新建资源
     */

    @RequestMapping(method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResultDTO<UserDTO> create(@RequestBody @Valid final UserDTO userDTO) {
        final User model = this.userConvertor.toModel(userDTO);
        this.userService.create(model);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was created.", User.class.getSimpleName(), model.getId());
        }
        return this.userConvertor.toResultDTO(model);
    }

    /**
     * 更新操作
     *
     * @param id 更新资源的ID
     * @param userDTO 更新资源的DTO
     * @return 更新后资源
     */

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResultDTO<UserDTO> update(@PathVariable final Long id, @RequestBody @Valid final UserDTO userDTO) {
        userDTO.setId(id);
        final User model = this.userConvertor.toModel(userDTO);
        this.userService.update(model);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was updated.", User.class.getSimpleName(), model.getId());
        }
        return this.userConvertor.toResultDTO(model);
    }

    /**
     * 删除操作
     *
     * @param Id 资源ID
     * @return 操作结果
     */

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResultDTO<Void> delete(@PathVariable final Long id) {
        this.userService.delete(id);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was deleted.", User.class.getSimpleName(), id);
        }
        return ResultDTO.success();
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ResultDTO<User> info(HttpServletRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            if (authentication instanceof AnonymousAuthenticationToken) {
                return null;
            }
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                return  ResultDTO.success((User) authentication.getPrincipal());
            }
        }
        return null;
    }
    @PostMapping(value = "/updatePass")
    public ResponseEntity updatePass(@RequestBody UserPassVo user){
        LoginUserBean userDetails = SecurityUtils.getUserDetails();
        if(!userDetails.getPassword().equals(user.getOldPass())){
            throw new CustomRuntimeException("406","修改失败，旧密码错误");
        }
        if(userDetails.getPassword().equals(user.getNewPass())){
            throw new CustomRuntimeException("406","修改失败，旧密码不能与新密码相同");
        }
        userService.updatePass(userDetails.getUsername(),user.getNewPass());
        return new ResponseEntity(HttpStatus.OK);
    }

}
